const NodeRSA = require('node-rsa')

const generateKeyPair = function () {
    var keyPair = new NodeRSA({ b: 2048 });
    keyPair.setOptions({ encryptionScheme: 'pkcs1' });

    const publicKey = keyPair.exportKey('pkcs1-public')
    const privateKey = keyPair.exportKey('pkcs1-private')
    let cleanPublicKey = publicKey.replace('-----BEGIN RSA PUBLIC KEY-----\n', '').replace('\n-----END RSA PUBLIC KEY-----', '');
    let cleanPrivateKey = privateKey.replace('-----BEGIN RSA PRIVATE KEY-----\n', '').replace('\n-----END RSA PRIVATE KEY-----', '');

    return [Buffer.from(cleanPublicKey).toString('base64'), cleanPrivateKey]
}

const encryptByPublicKey = function (publicKey, data) {
    const dePublicKey = Buffer.from(publicKey, 'base64').toString()
    const publicKeyPem = '-----BEGIN RSA PUBLIC KEY-----\n' + dePublicKey + '\n-----END RSA PUBLIC KEY-----'
    var encrypt = new NodeRSA(publicKeyPem, 'pkcs1-public')
    encrypt.setOptions({ encryptionScheme: 'pkcs1' })
    return encrypt.encrypt(data, 'base64', 'utf-8');
}

const decryptByPrivateKey = function (privateKey, data) {
    const privateKeyPem = '-----BEGIN RSA PRIVATE KEY-----\n' + privateKey + '\n-----END RSA PRIVATE KEY-----'
    var decrypt = new NodeRSA(privateKeyPem, 'pkcs1-private')
    decrypt.setOptions({ encryptionScheme: 'pkcs1' })
    return decrypt.decrypt(data, 'utf-8')
}

exports.generateKeyPair = generateKeyPair
exports.encryptByPublicKey = encryptByPublicKey
exports.decryptByPrivateKey = decryptByPrivateKey